package org.sample.commons.edoc;

import java.io.*;
import java.nio.charset.Charset;
import java.util.Collection;

public class CsvUtils {

    public static <T> void write(Columns columns, Collection<T> dataSet, OutputStream os) throws IOException {
        write(columns, dataSet, os, Charset.forName("GBK"));
    }

    public static <T> void write(Columns columns, Collection<T> dataSet, OutputStream os, Charset charset) throws IOException {
        Writer osw = new OutputStreamWriter(os, charset);
        BufferedWriter bw = new BufferedWriter(osw);

        StringBuilder row = new StringBuilder();
        for (Column column : columns.columns)
            row.append(column.title).append(",");

        bw.write(row.toString());
        bw.newLine();

        for (T data : dataSet) {
            row = new StringBuilder();
            for (Column column : columns.columns) {
                String value = column.readValue(data);

                boolean containsDQ;
                if (containsDQ = value.contains("\""))
                    value = value.replaceAll("\"", "\"\"");

                if (value.contains(",") || containsDQ)
                    row.append("\"").append("\t").append(value).append("\",");
                else
                    row.append("\t").append(value).append(",");
            }
            bw.write(row.toString());
            bw.newLine();
            bw.flush();
        }
        osw.flush();
    }

}